package com.may.utils;

import cn.hutool.core.lang.Console;
import com.may.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.Assert;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: dubbo-nacos
 * @description:
 * @author: Bobby.Ma
 * @create: 2020-07-08 21:44
 **/
public class HtmlParseUtil {

    public static List<Content> parseJDSearch(String searchKey){
        String url = String.format("https://search.jd.com/Search?keyword=%s",searchKey);
        Document document = null;
        try {
            document = Jsoup.parse(new URL(url), 30000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Assert.notNull(document,"没有 document！");
        Element element = document.getElementById("J_goodsList");
        Elements lis = element.getElementsByTag("li");
        return lis.stream().map(li ->
                new Content().setImg(li.getElementsByTag("img").eq(0).attr("src"))
                        .setName(li.getElementsByClass("p-name").eq(0).text())
                        .setPrice(li.getElementsByClass("p-price").eq(0).text())
        ).collect(Collectors.toList());
    }
}
